﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using BL;
using BL.Model.Request;
using Common;
using DAL.Model;
using DevExpress.XtraGrid.Views.Grid;

namespace UI.MainFunctions
{
    public partial class frmStockOutManager : Base.DialogViewBase
    {
        #region Private variables

        private MasterSession _session;
        private readonly StockOutController _stockOutController;

        #endregion

        #region Constructor

        public frmStockOutManager()
        {
            InitializeComponent();
            _session = new MasterSession();
            _stockOutController = new StockOutController(_session);
        }

        #endregion

        #region Overided methods

        protected override void InitializeBO()
        {
            base.InitializeBO();
            if (_session == null)
            {
                _session = new MasterSession();
            }
        }

        protected override void PopulateStaticData()
        {
            base.PopulateStaticData();
            deFromDate.DateTime = DateTime.Now.AddDays(-7);
            deToDate.DateTime = DateTime.Now;
            LoadCustomers();
            LoadProductCats();
        }

        protected override void PopulateData()
        {
            base.PopulateData();

            DateTime fromDate = deFromDate.DateTime > Constant.MinDate
                        ? deFromDate.DateTime.Date
                        : Constant.MinDate;
            DateTime toDate = deToDate.DateTime < Constant.MaxDate
                                  ? deToDate.DateTime.Date.AddDays(1)
                                  : Constant.MaxDate;

            var request = new SearchingStockOutRequest
                              {
                                  FromTime = fromDate,
                                  ToTime = toDate,
                                  IsPaging = false,
                                  DocumentNo = txtDocumentNo.Text,
                                  ProductCode = txtProductCode.Text,
                                  StockInNo = txtStockInNo.Text,
                                  TransferNo = txtTransferNo.Text,

                              };

            int customerId;
            if (lueCustomers.EditValue != null && int.TryParse(lueCustomers.EditValue.ToString(), out customerId))
            {
                request.CustomerIds = new List<int> { customerId };
            }
            else
            {
                request.CustomerIds = new List<int> { Constant.AllValue };
            }
            int productCategoryId;
            if (lueProductCat.EditValue != null && int.TryParse(lueProductCat.EditValue.ToString(), out productCategoryId))
            {
                request.ProductCategoryIds = new List<int> { productCategoryId };
            }
            else
            {
                request.ProductCategoryIds = new List<int> { Constant.AllValue };
            }

            var stockOuts = _stockOutController.Search(request);
            dgStockOut.DataSource = null;
            dgStockOut.DataSource = stockOuts;
            gvStockOut.BestFitColumns();

            var rowCount = stockOuts.Count;
            for (int i = 0; i < rowCount; i++)
            {
                gvStockOut.ExpandMasterRow(i);
                var detailView = (GridView)gvStockOut.GetDetailView(i, 0);
                detailView.ExpandAllGroups();
            }
        }

        protected override void FormatPrecision()
        {
            PrecisionHelper.FormatCurencyPrecision(gcStockInQuantity,
                                                   gcMassQuantity,
                                                   gcQuantity,
                                                   gcPrice,
                                                   gcSubTotal,
                                                   gcTotalQuantity,
                                                   gcTotal,
                                                   gcDiscount);
        }

        #endregion

        #region Private methods

        private void LoadCustomers()
        {
            var customers = _session.Customers.OrderBy(t => t.Name).ToList();
            customers.Insert(0, new Customer { Id = -1, Name = string.Empty });
            lueCustomers.Properties.DataSource = customers;
        }

        private void LoadProductCats()
        {
            var productCats = _session.ProductCategories.ToList();
            productCats.Insert(0, new ProductCategory { Id = -1, Name = string.Empty });
            lueProductCat.Properties.DataSource = productCats;
        }

        #endregion

        #region Events

        private void spFind_Click(object sender, EventArgs e)
        {
            PopulateData();
        }

        private void spView_Click(object sender, EventArgs e)
        {
            var stockOut = (StockOut)gvStockOut.GetRow(gvStockOut.FocusedRowHandle);
            if (stockOut == null)
            {
                return;
            }
            var frmStockOut = new frmStockOut(stockOut.Id, FormAction.View)
                                  {
                                      MdiParent = MdiParent
                                  };
            frmStockOut.Show();
        }

        private void spAdd_Click(object sender, EventArgs e)
        {

        }

        private void spEdit_Click(object sender, EventArgs e)
        {
            var stockOut = (StockOut)gvStockOut.GetRow(gvStockOut.FocusedRowHandle);
            if (stockOut == null)
            {
                return;
            }
            var frmStockOut = new frmStockOut(stockOut.Id, FormAction.Edit)
                                  {
                                      MdiParent = MdiParent
                                  };
            frmStockOut.Show();
        }

        private void spReceipt_Click(object sender, EventArgs e)
        {
            var rows = gvStockOut.GetSelectedRows();
            var ids = new List<int>();
            foreach (var index in rows)
            {
                var cell = gvStockOut.GetRowCellValue(index, "Id");
                int value;
                if (cell != null && int.TryParse(cell.ToString(), out value))
                {
                    ids.Add(value);
                }
            }
            var receipt = new frmReceipt
            {
                StockOutIds = ids,
                MdiParent = MdiParent
            };
            receipt.Show();
        }
        
        private void gvStockOut_MasterRowEmpty(object sender, MasterRowEmptyEventArgs e)
        {
            var row = (StockOut)gvStockOut.GetRow(e.RowHandle);
            e.IsEmpty = row.StockOutDetails.Count == 0;
        }

        private void gvStockOut_MasterRowGetChildList(object sender, MasterRowGetChildListEventArgs e)
        {
            var row = (StockOut)gvStockOut.GetRow(e.RowHandle);
            e.ChildList = new BindingSource(row, "StockOutDetails");
        }

        private void gvStockOut_MasterRowGetRelationCount(object sender, MasterRowGetRelationCountEventArgs e)
        {
            e.RelationCount = 1;
        }

        private void gvStockOut_MasterRowGetRelationName(object sender, MasterRowGetRelationNameEventArgs e)
        {
            e.RelationName = "StockOutDetails";
        }

        #endregion
    }
}
